#include "ReutersXMLParser.hpp"

#include "ReutersDocument.hpp"


ReutersXMLParser::ReutersXMLParser (ReutersDocument* document) :
    document_ (document),
    d_ (false)
{}


bool ReutersXMLParser::startElement (const QString&, const QString& localName, const QString&, const QXmlAttributes&) {
    if (localName == "DATE") {
        tag_ = NowReading::Date;
    } else if (localName == "TOPICS") {
        tag_ = NowReading::Topics;
    } else if (localName == "PLACES") {
        tag_ = NowReading::Places;
    } else if (localName == "PEOPLE") {
        tag_ = NowReading::People;
    } else if (localName == "ORGS") {
        tag_ = NowReading::Orgs;
    } else if (localName == "EXCHANGES") {
        tag_ = NowReading::Exchanges;
    } else if (localName == "COMPANIES") {
        tag_ = NowReading::Companies;
    } else if (localName == "DATELINE") {
        tag_ = NowReading::Dateline;
    } else if (localName == "BODY") {
        tag_ = NowReading::Body;
    } else if (localName == "D") {
        d_ = true;
    } else {
        tag_ = NowReading::never_mind_just_ignore_this_tag;
    }
    return true;
}


bool ReutersXMLParser::characters (const QString& content) {
    if (tag_ == NowReading::Date) {
        document_->setDateline(content);
    } else if (tag_ == NowReading::Body) {
        document_->setBody(content);
    } else if (tag_ == NowReading::Dateline) {
        // we use date as dateline as it is prettier :P
        // document_->setDateline(content);
    } else if (d_){
        switch (tag_) {
        case NowReading::Topics:
            document_->addTopic(content);
            break;
        case NowReading::Places:
            document_->addPlace(content);
            break;
        case NowReading::People:
            document_->addPerson(content);
            break;
        case NowReading::Orgs:
            document_->addOrg(content);
            break;
        case NowReading::Exchanges:
            document_->addExchange(content);
            break;
        case NowReading::Companies:
            document_->addCompany(content);
            break;
        default:
            break;
        }
    }
    return true;
}


bool ReutersXMLParser::endElement (const QString&, const QString& localName, const QString&) {
    if (localName == "D") {
        d_ = false;
    } else {
        tag_ = NowReading::never_mind_just_ignore_this_tag;
    }
    return true;
}


bool ReutersXMLParser::startDocument() {

    return true;
}


bool ReutersXMLParser::endDocument() {
    document_->setLoaded (true);
    return true;
}
